﻿
// Note: 
// Strange we need this since wp7.1's System.Core library seems to included Lazy<T>, but I can't initialize it http://yfrog.com/z/18rjpp
// 25-9-2011
#if (WP7)

using System;
using nRoute.Utilities;
using System.Threading;

namespace nRoute.Components
{
    /// <remarks>from MEF http://mef.codeplex.com/SourceControl/changeset/view/34058#484572
    /// to be removed when moving to SL4. Also, note_ uses TypeActivator rather than Activator and 
    /// we've added the IsValueCreated property to match SL4 version.</remarks>
    public class Lazy<T>
    {
        private T _value = default(T);
        private volatile bool _isValueCreated = false;
        private Func<T> _valueFactory = null;
        private readonly object _lock;

        public Lazy()
            : this(TypeActivator.CreateInstance<T>) { }

        public Lazy(bool isThreadSafe)
            : this(TypeActivator.CreateInstance<T>, isThreadSafe) { }

        public Lazy(Func<T> valueFactory) 
            : this(valueFactory, true) { }

        public Lazy(Func<T> valueFactory, bool isThreadSafe)
        {
            Guard.ArgumentNotNull(valueFactory, "valueFactory");
            if (isThreadSafe)
            {
                this._lock = new object();
            }

            this._valueFactory = valueFactory;
        }

#region Properties

        public bool IsValueCreated
        {
            get { return _isValueCreated; }
        }

        public T Value
        {
            get
            {
                if (!this._isValueCreated)
                {
                    if (this._lock != null)
                    {
                        Monitor.Enter(this._lock);
                    }

                    try
                    {
                        T value = this._valueFactory.Invoke();
                        this._valueFactory = null;
                        Thread.MemoryBarrier();
                        this._value = value;
                        this._isValueCreated = true;
                    }
                    finally
                    {
                        if (this._lock != null)
                        {
                            Monitor.Exit(this._lock);
                        }
                    }
                }
                return this._value;
            }
        }

#endregion

    }
}

#endif